package controllers

import (
	"main/src/models"

	"github.com/gofiber/fiber/v2"
)

func GetAllOrgs(c *fiber.Ctx) error {
	orgs, err := models.FetchAllOrgs()
	if err != nil {
		return c.JSON(fiber.Map{"message": err.Error()})
	}
	return c.JSON(fiber.Map{"message": "Orgs fetched successfully", "status": "success", "data": orgs})
}

func GetOrgByID(c *fiber.Ctx) error {
	orgID := c.AllParams()["id"]
	if orgID == "" {
		return c.JSON(fiber.Map{"message": "Org ID is required"})
	}
	org, err := models.FetchOrg(orgID)
	if err != nil {
		return c.JSON(fiber.Map{"message": err.Error()})
	}
	return c.JSON(fiber.Map{"message": "Org fetched successfully", "status": "success", "data": org})
}

func CreateOrg(c *fiber.Ctx) error {
	orgModel := new(models.Org)

	if err := c.BodyParser(orgModel); err != nil {
		return c.JSON(fiber.Map{"status": "failed parse model", "message": err.Error(), "data": nil})
	}

	savedOrg, err := orgModel.Save()

	if err != nil {
		return c.JSON(fiber.Map{"status": "failed save in db", "message": err.Error(), "data": nil})
	}

	return c.JSON(fiber.Map{"status": "success", "message": "Org saved successfully", "data": savedOrg})
}

func UpdateOrg(c *fiber.Ctx) error {
	OrgID := c.AllParams()["id"]
	if OrgID == "" {
		return c.JSON(fiber.Map{"message": "Org ID is required"})
	}

	var updatedOrg *models.Org

	if err := c.BodyParser(&updatedOrg); err != nil {
		return c.JSON(fiber.Map{"status": "failed", "message": err.Error(), "data": nil})
	}

	updatedOrg, err := updatedOrg.UpdateOrg(OrgID)
	if err != nil {
		return c.JSON(fiber.Map{"status": "failed", "message": err.Error(), "data": nil})
	}

	return c.JSON(fiber.Map{"status": "success", "message": "Org updated successfully", "data": updatedOrg})
}

func DeleteOrg(c *fiber.Ctx) error {
	OrgID := c.AllParams()["id"]
	if OrgID == "" {
		return c.JSON(fiber.Map{"message": "Org ID is required"})
	}

	err := models.DeleteOrg(OrgID)
	if err != nil {
		return c.JSON(fiber.Map{"message": err.Error()})
	}

	return c.JSON(fiber.Map{"message": "Org deleted successfully", "status": "success", "data": nil})
}
